package org.linlinjava.litemall.wx.controller;

import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.PayPalRESTException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.payment.paypal.service.impl.GoodsPaypalServiceImpl;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.service.LitemallRechargeConsumptionService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.wx.annotation.LogAnno;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.WxCloverPayService;
import org.linlinjava.litemall.wx.util.RewardsUtils;
import org.linlinjava.litemall.wx.util.URLUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * 贝宝控制器
 *
 * @author yliyun
 * @description：TODO
 * @date 2022/09/14
 */

@Controller
public class PaypalController {
    /**
     * 贝宝成功url
     */
    @Value("${paypal.paypal_goods_success_url}")
    public String PAYPAL_SUCCESS_URL;
    /**
     * 贝宝取消url
     */
    @Value("${paypal.paypal_goods_cancel_url}")
    public String PAYPAL_CANCEL_URL;

    /**
     * 贝宝充电成功url
     */
    public static final String PAYPAL_RECHARGE_SUCCESS_URL = "wx/paypal/recharge/success";
    /**
     * 贝宝取消url充电
     */
    public static final String PAYPAL_RECHARGE_CANCEL_URL = "wx/paypal/recharge/cancel";

    /**
     * 出版商
     */
    @Autowired
    private ApplicationEventPublisher publisher;

    /**
     * 日志
     */
    private Log log = LogFactory.getLog(PaypalController.class);

    /**
     * 订单服务
     */
    @Autowired
    private LitemallOrderService orderService;

    /**
     * url跑龙套
     */
    @Autowired
    private URLUtils urlUtils;

    /**
     * 贝宝服务
     */
    @Autowired
    private GoodsPaypalServiceImpl paypalService;

    /**
     * 三叶草支付服务
     */
    @Autowired
    private WxCloverPayService cloverPayService;

    /**
     * 奖励跑龙套
     */
    @Autowired
    private RewardsUtils rewardsUtils;


    /**
     * litemall充电消费服务
     */
    @Autowired
    private LitemallRechargeConsumptionService litemallRechargeConsumptionService;

    @Autowired
    private LitemallUserService userService;

    /**
     * 支付
     *
     * @param request 请求
     * @param userId  用户id
     * @param orderId 订单id
     * @return {@link Object}
     */
    @GetMapping("/wx/paypal/pay")
    @LogAnno
    public Object pay(HttpServletRequest request, @LoginUser Integer userId, @NotNull Integer orderId) {
        String cancelUrl = urlUtils.getBaseURl() + PAYPAL_CANCEL_URL;
        String successUrl = urlUtils.getBaseURl() + PAYPAL_SUCCESS_URL;

        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        Object obj =  paypalService.getPayment(userId, orderId, PAYPAL_SUCCESS_URL, PAYPAL_CANCEL_URL,"");
        if(!(obj instanceof Payment)){
            return obj;
        }

        Payment payment = (Payment)obj;
        for(Links links : payment.getLinks()){
            if(links.getRel().equals("approval_url")){
//                return String.format("<script type=\"text/javascript\">location.href=\"%s\"</script>",links.getHref() );
                return "redirect:" + links.getHref();
            }
        }

        return "<script type=\"text/javascript\">location.href=\"/\"</script>" ;
    }

    /**
     * 取消支付
     *
     * @return {@link Object}
     */
    @GetMapping("/wx/paypal/cancel")
    @LogAnno
    public Object cancelPay(){
        return ResponseUtil.ok("cancel") ;
    }

    /**
     * 成功支付
     *
     * @param paymentId 支付id
     * @param payerId   付款人身份
     * @return {@link Object}
     */
    @GetMapping("/wx/paypal/success")
    @LogAnno
    @Transactional
    public Object successPay( @RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId){
        log.debug("paypal success");
        try {
            LitemallOrder order = orderService.findByOutTradeNo(paymentId);
            rewardsUtils.getRewardInConsum(order.getUserId());
            Object obj =  paypalService.executePayment(paymentId, payerId);

            if(!(obj instanceof Payment)){
                return obj;
            }
            Payment payment = (Payment)obj;
            if(payment.getState().equals("approved")){
                //是否第一次消费
//                LitemallOrder order = orderService.findByOutTradeNo(paymentId);
//                publisher.publishEvent(new MemberEvent(paymentId));
                paypalService.presentPoint(order.getId(),null);
                //用户 等级会员的提升
                paypalService.upgradeUserLevel(order.getId());

//                cloverPayService.getRewards(order.getUserId());

                return ResponseUtil.ok("success");
            }
        } catch (PayPalRESTException e) {
            log.error(e.getMessage());
        }
        return "<script type=\"text/javascript\">location.href=\"/\"</script>" ;
    }


    /**
     * 充电
     * 用户充值
     *
     * @param request 请求
     * @param userId  用户id
     * @param amount  量
     * @return {@link Object}
     */
    @GetMapping("/wx/paypal/recharge")
    @LogAnno
    public Object recharge(HttpServletRequest request, @LoginUser Integer userId, BigDecimal amount){
        String cancelUrl = urlUtils.getBaseURl() + "/" + PAYPAL_RECHARGE_CANCEL_URL;
        String successUrl = urlUtils.getBaseURl() + "/" + PAYPAL_RECHARGE_SUCCESS_URL;
        Object obj =  new Object();
        if(!(obj instanceof Payment)){
            return obj;
        }

        Payment payment = (Payment)obj;
        for(Links links : payment.getLinks()){
            if(links.getRel().equals("approval_url")){
                return "redirect:" + links.getHref();
            }
        }

        return "<script type=\"text/javascript\">location.href=\"/\"</script>" ;
    }
}
